package main

import (
	"bufio"
	"os/exec"
	"strings"

	"os"

	"fmt"

	"github.com/go-vgo/robotgo"
)

func main() {
	for {
		fmt.Println("--- Please press a ---")
		if robotgo.AddEvent("a") == 0 {
			CapturePhonePic() // 运行程序立马就截屏并保存问题
			subject := OcrFindWord("screenshot.png", "screenshot")

			// 将鼠标点击到搜索框中,程序自动输入并搜索
			robotgo.MouseClick("left", true)
			robotgo.KeyTap("a", "control")
			robotgo.TypeString(subject)
			robotgo.KeyTap("enter")
		}
	} // for
}

/**
* 输入文件路径
* 输出识别结果到文件中
* 并返回文件内容
**/
func OcrFindWord(file, output string) string {
	cmd := exec.Command("E:\\Program_Files\\Tesseract-OCR\\tesseract.exe", file, output, "-l", "chi_sim")
	if _, err := cmd.Output(); err != nil {
		panic(err)
	}

	fr, err := os.Open(output + ".txt")
	if err != nil {
		panic(err)
	}
	defer fr.Close()

	var (
		buf     = bufio.NewReader(fr)
		subject string
	)
	for {
		line, err := buf.ReadString('\n')
		if err != nil {
			break
		}

		line = strings.Replace(strings.TrimSpace(line), " ", "", -1)
		if strings.LastIndex(line, "?") > 0 {
			subject += line
			break
		}

		subject = line // 缓存上次结果最多就2行
	}

	return subject
}

/**
* 为手机截屏
* 并将图片上传到本地
//（保存到SDCard）
adb shell /system/bin/screencap -p /sdcard/screenshot.png
// 从SD卡导出到电脑，注意 F:\\mvp 为电脑路径，必须存在
adb pull /sdcard/screenshot.png F:\\mvp（保存到电脑）
adb shell rm /sdcard/screen.png
adb shell screencap -p | sed 's/\r$//' > screen.png
**/
func CapturePhonePic() {
	cmd := exec.Command(".\\adb\\adb.exe", "shell", "/system/bin/screencap", "-p", "/sdcard/screenshot.png")
	if _, err := cmd.Output(); err != nil {
		panic(err)
	}

	cmd = exec.Command(".\\adb\\adb.exe", "pull", "/sdcard/screenshot.png")
	if _, err := cmd.Output(); err != nil {
		panic(err)
	}
}
